package com.zhuhjay.chat.client;

import com.zhuhjay.chat.client.handler.*;
import com.zhuhjay.chat.config.Config;
import com.zhuhjay.chat.protocol.MessageCodecSharable;
import com.zhuhjay.chat.protocol.ProcotolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ZhuHJay
 */
@Slf4j
public class ClientBoot {
    /** 工作线程 **/
    private final NioEventLoopGroup group = new NioEventLoopGroup();
    /** 处理器 **/
    private final MessageCodecSharable messageCodec = new MessageCodecSharable();
    private final HeartbeatTransferHandler heartbeatHandler = new HeartbeatTransferHandler();
    private final LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
    /** 连接端口 **/
    private final String host;
    private final int port;
    private Channel channel;

    public ClientBoot() {
        this(Config.getHost(), Config.getPort());
    }

    public ClientBoot(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public Channel getChannel() {
        return channel;
    }

    /** 客户端连接服务器，如果是RPC测试则只专注RPC **/
    public ClientBoot run(boolean isRpc) {
        ChannelFuture channelFuture = new Bootstrap()
                .channel(NioSocketChannel.class)
                .group(group)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ProcotolFrameDecoder());
                        if (Config.isDebug()) {
                            ch.pipeline().addLast(loggingHandler);
                        }
                        ch.pipeline().addLast(messageCodec);
                        // -- 心跳
                        ch.pipeline().addLast(new IdleStateHandler(0, 3, 0));
                        ch.pipeline().addLast(heartbeatHandler);
                        // -- 业务
                        LoginResponseMessageHandler loginMessage = new LoginResponseMessageHandler();
                        ch.pipeline().addLast(loginMessage);
                        AbstractResponseMessageHandler.SHARABLE_HANDLERS.forEach(handler -> ch.pipeline().addLast(handler));
                        // RPC 调用就不进行聊天服务了
                        if (!isRpc) {
                            ch.pipeline().addLast(new ConsoleInputMessageHandler(loginMessage));
                        }
                    }
                }).connect(host, port);
        try {
            channel = channelFuture.sync().channel();
            channel.closeFuture().addListener(future -> group.shutdownGracefully());
        } catch (InterruptedException e) {
            throw new RuntimeException("客户端启动失败");
        }
        return this;
    }


}
